package com.xjtulpar.service.impl;

import com.xjtulpar.dao.itf.ManagerMapper;
import com.xjtulpar.entity.Manager;
import com.xjtulpar.service.itf.ManagerService;
import com.xjtulpar.utils.FileUploadUtils;
import com.xjtulpar.utils.PathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by Levi on 2017/10/10.
 */
@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    ManagerMapper managerMapper;

    public List<Manager> getAllManagers() {
        return managerMapper.queryAllManagers();
    }

    public Manager getById(int mId) {
        return managerMapper.queryById(mId);
    }

    public void addManager(Manager manager) {
        String url = "img/avatars/default.jpg";
        manager.setmPic(url);
        managerMapper.insertManager(manager);
    }

    public void updateManager(Manager manager) {

        managerMapper.updateManager(manager);
    }

    public void deleteManager(int mId) {
        managerMapper.deleteManager(mId);
    }

    @Override
    public void updateIcon(MultipartFile[] files, String mId) {
        for (MultipartFile multipartFile : files) {
            SimpleDateFormat sdf = new SimpleDateFormat("hh.mm.ss.SS");
            String dir = PathUtils.getRealPath("/img/avatars");
            String fileName = multipartFile.getOriginalFilename();
            String ends = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String currentTime = sdf.format(System.currentTimeMillis());
            String targetFileName = mId + "_" + currentTime + ends;
            FileUploadUtils.uploadFile(multipartFile, dir, targetFileName);
            String mPic = "/img/avatars/" + targetFileName;
            Manager manager = new Manager();
            manager.setmId(Integer.parseInt(mId));
            manager.setmPic(mPic);
            managerMapper.updateIcon(manager);
        }
    }
}
